package center_rpc

import (
	"common/pb"
	"context"
)

func (cRpc *CenterRpc) DownloadObject(ctx context.Context, bucket string, encObjectKey []byte) (*pb.ObjectDownloadResponse, error) {
	client, connClose, err := cRpc.getDrpcClient(ctx)
	if err != nil {
		return nil, Error.Wrap(err)
	}
	defer connClose()
	// set a deadline for the operation
	ctx, cancel := context.WithTimeout(ctx, cRpc.timeout)
	defer cancel()

	response, err := client.DownloadObject(ctx, &pb.ObjectDownloadRequest{
		Header:             cRpc.Header(),
		Bucket:             []byte(bucket),
		EncryptedObjectKey: encObjectKey,
		Limit:              0,
	})
	if err != nil {
		return nil, Error.Wrap(err)
	}
	if response == nil {
		return nil, Error.New("response is nil")
	}
	if response.Rs == nil {
		return nil, Error.New("rs_coder is nil")
	}
	return response, nil
}
